package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.TaskListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.OrderBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.task.TaskBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.task.TaskListResult;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.CommConstants;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.PageFlag;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Descriptions：任务记录列表
 * <p>
 * Author：ChenME
 * Date：2016/11/16
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_task_record_list)
public class TaskRecordListActivity extends AppBaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate, AppBaseActivity.OnRefreshBtnClickListener {

    @ViewById(R.id.refreshMyOrder)
    BGARefreshLayout refreshMyOrder;
    @ViewById(R.id.lv_myOrderList)
    RecyclerView lv_myOrderList;
    @ViewById(R.id.btn_placeOrder)
    Button btn_placeOrder;

    private List<TaskBean> taskList;
    private TaskListAdapter taskListAdapter;
    private int startPosition;

    private TaskRecordListActivity _activity;

    private LocalBroadcastManager lbm;

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastChannels.Channel_CreateOrderSuccessFully)) { // 下单成功
                finish();
                animUtils.leftOutAnimation(_activity);
//                getOrderRecordList(false, null);//获取数据
            }
        }
    };

    @AfterViews
    void startOrderRecord() {
        _activity = this;

        initRefreshView(_activity, refreshMyOrder, true, true);
        setTitle(this, R.string.string_title_my_order_record, R.drawable.comm_press_return_selector,
                true, new OnNavigationBtnClickListener() {
                    @Override
                    public void navigationClick() {
                        finish();
                        animUtils.leftOutAnimation(_activity);
                    }

                    @Override
                    public void menuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menuItem1:
                                OrderStatisticsActivity_.intent(_activity).start();
                                animUtils.leftInAnimation(_activity);
                                break;
                        }
                    }
                });

        bindOrderRecordList();//绑定数据
        setListener();
        registerBroadcast();
        getOrderRecordList(true, null);//获取数据
    }

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menuItem1).setVisible(true).setIcon(R.drawable.press_task_selector);
        menu.findItem(R.id.menuItem2).setVisible(false);
        return true;
    }

    /**
     * 设置监听器
     */
    private void setListener() {
        taskListAdapter.setOnItemClickListener(position -> {
//            OrderDetailActivity_.intent(_activity).orderId(taskList.get(position).getOrderId()).start();
            TaskDetailActivity_.intent(this).whichPage(PageFlag.Page_TaskRecordList).taskId(taskList.get(position).getMissionId()).start();
            animUtils.leftInAnimation(_activity);
        });
    }

    /**
     * 绑定记录列表数据
     */
    private void bindOrderRecordList() {
        taskList = new ArrayList<>();

        taskListAdapter = new TaskListAdapter(this, taskList, TaskListAdapter.Page_Record);
        refreshMyOrder.setDelegate(this);
        lv_myOrderList.setLayoutManager(new LinearLayoutManager(this));
        lv_myOrderList.setAdapter(taskListAdapter);
    }

    /**
     * 获取订单记录
     *
     * @param isClear       是否刷新
     * @param refreshLayout 刷新控件
     */
    private void getOrderRecordList(final boolean isClear, final BGARefreshLayout refreshLayout) {

        int si = startPosition;
        if (!isClear) {
            si += Value.listCount;
        }
        TaskBean bean = new TaskBean(String.valueOf(si), String.valueOf(Value.listCount), "2");
        String jsonRequest = JsonUtils.createJsonString(bean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_GetMissionList, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {

                    if (null != refreshLayout) {
                        if (isClear) {
                            refreshLayout.endRefreshing();
                        } else {
                            refreshLayout.endLoadingMore();
                        }
                    }

                    if (null != content) {
                        Object obj = JsonUtils.parseJsonString(content, TaskListResult.class);
                        if (obj instanceof TaskListResult) {
                            TaskListResult bean = (TaskListResult) obj;

                            if (isClear) {//刷新
                                if (!StringUtils.isEmpty(content)) {
                                    taskList.clear();
                                }
                            } else {
                                startPosition += Value.listCount;
                            }

                            taskList.addAll(bean.getInfolist());
                            taskListAdapter.notifyDataSetChanged();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                    setDateEmpty();
                    setCommenActivtiyType(CommConstants.TYPE_EMPTY, _activity);
                    if (isClear) {
                        taskList.clear();
                        if (null != refreshLayout) {
                            refreshLayout.endRefreshing();
                        }
                    }
                    if (null != refreshLayout) {
                        refreshLayout.endLoadingMore();
                    }
                }

                @Override
                public void onDataEnd(String content) {
                    App.toast(R.string.strings_common_dateEnd);
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    setCommenActivtiyType(CommConstants.TYPE_ERROR, _activity);
                    super.onErr(errorCode, errorMsg, mContext);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置数据为空
     */
    @UiThread
    void setDateEmpty() {
        taskList.clear();
        taskListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        startPosition = 0;
        getOrderRecordList(true, refreshLayout);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        getOrderRecordList(false, refreshLayout);
        return false;
    }

    /**
     * 下单按钮的点击事件
     */
    @Click(R.id.btn_placeOrder)
    void orderRecordPlace() {
        PlaceOrderActivityV2_.intent(_activity).fromWhichPage(Flag.ToPlaceOrder_FromMissionRecord).start();
        animUtils.leftInAnimation(this);
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastChannels.Channel_CreateOrderSuccessFully);
        lbm.registerReceiver(broadcastReceiver, filter);
    }

    /**
     * 刷新
     */
    @Override
    public void refreshClick() {
        getOrderRecordList(false, null);
    }
}